<?php

namespace App\Repositories\Impl;

use App\Models\News;
use App\Repositories\Contracts\NewsRepository;
use App\Repositories\Transformers\NewsListTransformer;
use App\Repositories\Transformers\NewsTransformer;

class NewsRepositoryImpl implements NewsRepository
{
    public function paginate($perPage, $filter)
    {
        $news = new News();

        if ($filter['type'] > 0) {
            $news = $news->where('type', $filter['type']);
        }
        if (!empty($filter['keyword'])) {
            $news = $news->where('title', 'like', '%' . $filter['keyword'] . '%');
        }

        $news = $news->orderBy('sort','desc')->orderBy('id', 'desc')->paginate($perPage);
        $result = fractal($news, new NewsListTransformer());

        return $result->toArray();
    }

    public function find($id, $columns = ['*'])
    {
        $news = News::find($id, $columns);
        $result = fractal($news, new NewsTransformer());

        return $result->toArray();
    }

    public function findByFilter($filter, $columns = ['*'])
    {
        return News::where($filter)->first($columns);
    }

    public function store($data)
    {
        return News::create($data);
    }

    public function update($data, $id)
    {
        return News::whereId($id)->update($data);
    }

    public function updateByFilter($data, $where)
    {
        return News::where($where)->update($data);
    }

    public function delete($id)
    {
        return News::whereId($id)->delete();
    }
}
